/*
 * @Author: your name
 * @Date: 2021-09-07 10:56:06
 * @LastEditTime: 2021-11-08 15:17:54
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \shanzhong-be\server.js
 */
/*
 * @Author: your name
 * @Date: 2021-06-19 09:53:04
 * @LastEditTime: 2021-09-08 10:19:23
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /shujucaiji/server.js
 */
const app = require('./app');
const debug = require('debug')('her:server');
const http = require('http');
// const io = require('socket.io')()
const { io } = require('./lib/utils/socket');

// 内部组件
const utils = require('./lib/utils');

// 配置文件
const CONFIG = require('./config');

// 获取定时任务
// const schedule = require('./lib/serve');

//设定服务端口号
let port = utils.normalizePort(process.env.PORT || CONFIG.PORT);

//创建HTTP服务
let server = http.createServer(app);

io.attach(server, {
  pingInterval: 10000,
  pingTimeout: 5000,
  cookie: false,
  cors: {
    origin: '*',
    methods: ['GET', 'POST'],
  },
});

io.on('connection', (socket) => {
  socket.emit('ready', 'socket 链接成功');
  socket.join('room1');
});

//监听服务端口
server.listen(port,()=>{
  // schedule();
  console.log('服务已经启用，端口号:'+port);
});


//服务器监听错误
server.on('error', (error)=>{

  if (error.syscall !== 'listen') throw error;

  let bind = typeof port === 'string'
    ? 'Pipe ' + port
    : 'Port ' + port;

  // 处理特殊错误
  switch (error.code) {
    case 'EACCES':
      console.error(bind + ' requires elevated privileges');
      process.exit(1);
    case 'EADDRINUSE':
      console.error(bind + ' 端口已被占用');
      process.exit(1);
    default:
      throw error;
  }
});


// 监听
server.on('listening', ()=>{

  let addr = server.address();
  let bind = typeof addr === 'string'
    ? 'pipe ' + addr
    : 'port ' + addr.port;
  debug('Listening on ' + bind);
});